package com.sh.pangea.dsa.Utils;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.sh.lib.dsa.bean.analyzeresult.LinearItem;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.bean.AnalyzeResult;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by TianGenhu on 2016/10/12.
 */

public class CustomAnalyzeBoard extends PopupWindow {
    private LineChart popwindowLineChart;
    private TextView line_chart_title;
    private boolean has_K = false;


    public CustomAnalyzeBoard(Context context, AnalyzeResult analyzeResult) {
        initView(context);
        if (analyzeResult != null) {

            String nameGraph = analyzeResult.getTitleGraph();
            if (nameGraph == null) {
                nameGraph = "";
            }
            getXString(analyzeResult);
            generateDataLine(analyzeResult.getyForGraph(), nameGraph);
            line_chart_title.setText(analyzeResult.getTitleGraph());
        }
    }

    private void initView(Context context) {
        View rootView = LayoutInflater.from(context).inflate(R.layout.custom_analyze_board, null);
        rootView.findViewById(R.id.popwindowLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        popwindowLineChart = (LineChart) rootView.findViewById(R.id.popwindow_line_chart);
        line_chart_title = (TextView) rootView.findViewById(R.id.line_chart_title);
        popwindowLineChart.getDescription().setEnabled(false);
        XAxis xAxis = popwindowLineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(mIAxisValueFormatter_X);
        //设置x轴字体显示角度,即X轴上文字呈现斜着显示
        xAxis.setLabelRotationAngle(0);
        //设置X轴的位置TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE, BOTTOM_INSIDE
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        YAxis leftAxis = popwindowLineChart.getAxisLeft();
        leftAxis.setInverted(false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setValueFormatter(mIAxisValueFormatter_Y);
        YAxis rightAxis = popwindowLineChart.getAxisRight();
        rightAxis.setEnabled(false);
//        rightAxis.setSpaceTop(15f);
        rightAxis.setValueFormatter(mIAxisValueFormatter_Y);
        rightAxis.setAxisMinimum(0f);
        popwindowLineChart.animateY(3000);
        // get the legend (only possible after setting data)
        Legend l = popwindowLineChart.getLegend();
        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        // dont forget to refresh the drawing
        popwindowLineChart.invalidate();
//        XYMarkerView mv = new XYMarkerView(context, mIAxisValueFormatter_X);
//        mv.setChartView(popwindowLineChart); // For bounds control
//        popwindowLineChart.setMarker(mv); // Set the marker to the chart

        setContentView(rootView);
        setOnTouch();
        setFocusable(true);
        setTouchable(true);
//        setBackgroundDrawable(new BitmapDrawable());
    }

    private final IAxisValueFormatter mIAxisValueFormatter_X = new IAxisValueFormatter() {

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            return ((int) value) + 1 + "";
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };

    private final DecimalFormat mFormat = new DecimalFormat("###,###,###,##0.0");
    private final IAxisValueFormatter mIAxisValueFormatter_Y = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String s;
            if (mFormat != null) {
                if (has_K) {
                    s = mFormat.format(value / 1000) + " K";
                } else {
                    s = mFormat.format(value);
                }
            } else {
                s = null;
            }
            return s;
        }

        @Override
        public int getDecimalDigits() {
            return 0;
        }
    };


    private void setOnTouch() {
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
    }

    /**
     * generates a random ChartData object with just one DataSet
     */
    public void generateDataLine(List<LinearItem> linearItems, String nameGraph) {
        if (linearItems != null && linearItems.size() > 0) {
            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            LineDataSet set1;
            for (int a = 0; a < linearItems.size(); a++) {
                ArrayList<Entry> yVals1 = new ArrayList<Entry>();
                LinearItem linearItem = linearItems.get(a);
                List<Integer> data = linearItem.getData();
                for (int i = 0; i < data.size(); i++) {
                    int i1 = data.get(i);
                    if (i1 > 1000) {
                        has_K = true;
                    }
                    yVals1.add(new Entry(i, i1));
                }
                if (popwindowLineChart.getData() != null &&
                        popwindowLineChart.getData().getDataSetCount() > 0) {
                    set1 = (LineDataSet) popwindowLineChart.getData().getDataSetByIndex(a);
                    set1.setValues(yVals1);
                } else {
                    set1 = new LineDataSet(yVals1, nameGraph);
                    if (a % 2 == 0) {
                        Log.i("TGH", "setData: " + a);
                        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                    } else {
                        set1.setAxisDependency(YAxis.AxisDependency.RIGHT);

                    }
                    int number = AnalyzeStringUtil.getInstance().getNumber(a);
                    set1.setColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                    set1.setFillColor(AnalyzeStringUtil.getInstance().COLORS[number]);
                    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                    set1.setCircleColor(Color.WHITE);
                    set1.setLineWidth(2f);
                    set1.setCircleRadius(3f);
                    set1.setFillAlpha(65);

                    set1.setHighLightColor(Color.rgb(244, 117, 117));
                    set1.setDrawCircleHole(false);
                    dataSets.add(set1); // add the datasets
                }

            }
            if (popwindowLineChart.getData() != null &&
                    popwindowLineChart.getData().getDataSetCount() > 0) {
                popwindowLineChart.getData().notifyDataChanged();
                popwindowLineChart.notifyDataSetChanged();
            } else {
                // create a data object with the datasets
                LineData data = new LineData(dataSets);
                data.setValueTextColor(Color.WHITE);
                data.setValueTextSize(9f);
                // set data
                popwindowLineChart.setData(data);
            }
        } else {
            Log.i("TGH", "POPWind generateDataLine: linearItems list is null ");
        }

    }


    private void getXString(AnalyzeResult analyzeResult) {
//        if (analyzeResult != null) {
//            List<String> xList = analyzeResult.getxForGraph();
//            if (xList != null && xList.size() > 0) {
//                xForGraph = xList;
//            } else {
//                Log.i(TAG, "getXString: xList is null");
//            }
//        } else {
//            Log.i(TAG, "getXString: mAnalyzeResult is null");
//        }

    }

}
